package com.harmonk.firstscene.ui

import android.app.Application
import android.content.Intent
import android.util.Log
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat.startActivity
import androidx.lifecycle.viewmodel.compose.viewModel
import com.harmonk.firstscene.constants.CommonConstants
import com.harmonk.firstscene.constants.Utils
import com.harmonk.firstscene.db.entity.EventWithAll
import com.harmonk.firstscene.db.entity.Road
import com.harmonk.firstscene.ui.model.EventWithAllViewModel
import com.harmonk.firstscene.ui.model.EventWithAllViewModelFactory
import com.harmonk.firstscene.ui.model.RoadViewModel
import com.harmonk.firstscene.ui.model.RoadViewModelFactory

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ReportScreen(
    onBackClick: () -> Unit,
    eventId: Long
) {
    val context = LocalContext.current
    val viewModel: EventWithAllViewModel = viewModel(
        factory = EventWithAllViewModelFactory(LocalContext.current.applicationContext as Application)
    )
    val eventWithAll by viewModel.currentEventWithAll.observeAsState()
    val roadViewModel: RoadViewModel = viewModel(
        factory = RoadViewModelFactory(LocalContext.current.applicationContext as Application)
    )
    val roads by roadViewModel.roads.observeAsState(emptyList())
    var checkState by remember { mutableStateOf(CheckState()) }
    var eventInfoText by remember { mutableStateOf("") }
    var elementsText by remember { mutableStateOf("") }
    var eventNotesText by remember { mutableStateOf("") }
    var reportText by remember { mutableStateOf("") }
    fun getReportTexts(eventWithAll: EventWithAll, road: Road?) {
        eventInfoText = ""
        eventInfoText += "【时间】" + Utils.TimeFormatter.formatYearMonthDayWithHourMinute(
            eventWithAll.trafficEvent.timestamp
        )
        eventInfoText += "\n【地点】" + Utils.locationFormat(
            road,
            eventWithAll.trafficEvent.direction,
            eventWithAll.trafficEvent.isMainLine,
            eventWithAll.trafficEvent.kilometer,
            eventWithAll.trafficEvent.meter,
            eventWithAll.trafficEvent.location
        )
        eventInfoText += "\n【描述】${eventWithAll.trafficEvent.brief}"
        eventInfoText += "\n【损伤】${if (eventWithAll.trafficEvent.haveVehicleDamage) "车损" else ""}" +
                " ${if (eventWithAll.trafficEvent.haveInjuries) "人伤" else ""}" +
                " ${if (eventWithAll.trafficEvent.haveRoadPropertyLoss) "路产" else ""}" +
                " ${if (eventWithAll.trafficEvent.haveGoodsLoss) "货损" else ""}" +
                " ${if (eventWithAll.trafficEvent.haveRescueExpenses) "施救费" else ""}"

        elementsText = "\n【人车】"
        eventWithAll.vehicles.forEachIndexed { index, vehicle ->
            elementsText += "\n${index + 1}、${vehicle.name}，${vehicle.carNo}，${CommonConstants.VEHICLE_TYPES[vehicle.type]}"
            // 遍历车辆所属的人员
            eventWithAll.persons.filter { it.vehicleId == vehicle.vehicleId }
                .forEachIndexed { index, person ->
                    elementsText += "\n  • ${CommonConstants.PERSON_SEATS[person.seat]}${person.name}，${person.phone}，${person.sfzId}，${person.memo}"
                }
        }
        eventWithAll.persons.filter { it.vehicleId == -1L }.forEachIndexed { index, person ->
            elementsText += "\n• ${CommonConstants.PERSON_SEATS[person.seat]}${person.name}，${person.phone}，${person.sfzId}，${person.memo}"
        }

        eventNotesText = "\n【记事】"
        eventWithAll.eventNotes.forEachIndexed { index, eventNote ->
            eventNotesText += "\n${Utils.TimeFormatter.formatHourMinute(eventNote.timestamp)}  ${eventNote.content}  ${
                if (eventNote.recordLatLong) Utils.CoordinateFormatter.formatLatitude(
                    eventNote.latitude
                ) + Utils.CoordinateFormatter.formatLongitude(eventNote.longitude) else ""
            }"
        }
    }

    LaunchedEffect(Unit) {
        viewModel.getEventWithAllById(eventId)
        roadViewModel.loadAllRoads()
    }

    LaunchedEffect(eventWithAll) {
        if (eventWithAll != null) {
            Log.i("EventWithAll", eventWithAll.toString())
            val road = roads.find { it.roadId == eventWithAll!!.trafficEvent.roadId }
            getReportTexts(eventWithAll!!, road)
            reportText = if (checkState.showEventInfo) eventInfoText else ""
            reportText += if (checkState.showElements) elementsText else ""
            reportText += if (checkState.showEventNotes) eventNotesText else ""
        }
    }

    LaunchedEffect(checkState) {
        reportText = if (checkState.showEventInfo) eventInfoText else ""
        reportText += if (checkState.showElements) elementsText else ""
        reportText += if (checkState.showEventNotes) eventNotesText else ""
    }
    Scaffold(
        topBar = {
            androidx.compose.material3.TopAppBar(
                title = { Text("生成报告") },
                navigationIcon = {
                    androidx.compose.material3.IconButton(onClick = onBackClick) {
                        androidx.compose.material3.Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                }
            )
        }
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.SpaceEvenly
        ) {
            OutlinedTextField(
                value = reportText,
                onValueChange = {
                    reportText = it
                },
                label = { Text("报告内容") },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(12.dp)
                    .weight(1f),
                textStyle = TextStyle(fontSize = 16.sp)
            )
            // 三个多选按钮，对应showEventInfo,showElements,showEventNotes
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(12.dp),
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Checkbox(
                    checked = checkState.showEventInfo,
                    onCheckedChange = {
                        checkState = checkState.copy(showEventInfo = it)
                    }
                )
                Text(text = "基本")
                // 填充空白
                Spacer(modifier = Modifier.weight(1f))
                Checkbox(
                    checked = checkState.showElements,
                    onCheckedChange = {
                        checkState = checkState.copy(showElements = it)
                    }
                )
                Text(text = "车人")
                Spacer(modifier = Modifier.weight(1f))
                Checkbox(
                    checked = checkState.showEventNotes,
                    onCheckedChange = {
                        checkState = checkState.copy(showEventNotes = it)
                    }
                )
                Text(text = "记事")
            }
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(12.dp)
            ) {
                // 分享reportText文本内容按钮
                OutlinedButton(
                    modifier = Modifier.fillMaxWidth(),
                    onClick = {
                        val sendIntent: Intent = Intent().apply {
                            action = Intent.ACTION_SEND
                            putExtra(Intent.EXTRA_TEXT, reportText)
                            type = "text/plain"
                        }
                        val shareIntent = Intent.createChooser(sendIntent, null)
                        startActivity(context, shareIntent, null)
                    }
                ) {
                    Text(text = "分享")
                }

            }
        }
    }

}

data class CheckState(
    var showEventInfo: Boolean = true,
    var showElements: Boolean = true,
    var showEventNotes: Boolean = true
)